package LeetCode刷题.暑假刷的算法;

import java.util.LinkedList;

/**
 * @program: Java_Study
 * @author: Xiaofan
 * @createTime: 2021-08-15 08:45
 * @description: Functions of this class is 二叉树镜像翻转
 **/
public class 二叉树镜像{
    public static class TNode {
        int val;
        TNode left, right;
    }

    private static TNode createTree(int nums[],int start,int end) {
        TNode T=null;
        if(start<=end){
            int mid=(start+end+1)>>1;
            T=new TNode();
            T.val=nums[mid];
            T.left=createTree(nums,start,mid-1);
            T.right=createTree(nums,mid+1,end);
        }
        return T;
    }
   public static void levelOrder(TNode T){
        if(T!=null){
            LinkedList<TNode> q=new LinkedList<>();
            q.add(T);
            TNode p;
            while (!q.isEmpty()){
                p=q.poll();
                System.out.print(p.val+" ");
                if(p.left!=null){
                    q.add(p.left);
                }
                if(p.right!=null){
                    q.add(p.right);
                }
            }
            System.out.println();
        }
   }

    private static TNode reverseTree(TNode T) {
        if(T!=null){
            reverseTree(T.left);//一直走到最左的节点，然后往回退的时候顺带进行翻转
            reverseTree(T.right);//一直走到最右的节点，然后往回退的时候顺带进行翻转
            TNode temp=T.left;
            T.left=T.right;
            T.right=temp;
        }
        return T;
    }
    public static void main(String args[]){
        int nums[]={1,2,3,4,5,6,7};
        TNode T=createTree(nums,0,nums.length-1);
        System.out.print("未翻转前树的层序遍历为：");
        levelOrder(T);
        T=reverseTree(T);
        System.out.print("翻转后树的层序遍历为：");
        levelOrder(T);
    }


}